home *** CD-ROM | disk | FTP | other *** search
/ The Very Best of Atari Inside / The Very Best of Atari Inside 1.iso / mint / mntlib43 / mntlib / textio.c < prev    next >
C/C++ Source or Header  |  1993-07-06  |  1KB  |  74 lines

  1. /*
  2.  * textio: read/write routines for text. These can be used in programs
  3.  * where read and write are used instead of the (preferred) stdio routines
  4.  * for manipulating text files, by doing something like
  5.  *  #define read _text_read
  6.  * Written by Eric R. Smith and placed in the public domain.
  7.  *
  8.  * Modified to fix a bug causing a premature EOF signal -
  9.  *   Michal Jaegermann, June 1991.
  10.  */
  11.  
  12. #include <stdio.h>
  13. #include <unistd.h>
  14. #include <support.h>
  15.  
  16. int
  17. _text_read(fd, buf, nbytes)
  18.     int fd;
  19.     char *buf;
  20.     int nbytes;
  21. {
  22.     char *to, *from;
  23.     int  r;
  24.  
  25.     do {
  26.         r = read(fd, buf, nbytes);
  27.         if (r <= 0)        /* if EOF or read error - return */
  28.             return r;
  29.         to = from = buf;
  30.         do {
  31.             if (*from == '\r')
  32.                 from++;
  33.             else
  34.                 *to++ = *from++;
  35.         } while (--r);
  36.     } while (buf == to);    /* only '\r's? - try to read next nbytes */
  37.     return (int)(to - buf);
  38. }
  39.  
  40. int
  41. _text_write(fd, from, nbytes)
  42.     int fd;
  43.     const char *from;
  44.     int nbytes;
  45. {
  46. #ifdef __SOZOBON__
  47.     char buf[1024+2];
  48. #else
  49.     char buf[BUFSIZ+2];
  50. #endif
  51.     char *to, c;
  52.     int  w, r, bytes_written;
  53.  
  54.     bytes_written = 0;
  55.     while (bytes_written < nbytes) {
  56.         w = 0;
  57.         to = buf;
  58.         while (w < BUFSIZ && bytes_written < nbytes) {
  59.             if ((c = *from++) == '\n') {
  60.                 *to++ = '\r'; *to++ = c;
  61.                 w += 2;
  62.             }
  63.             else {
  64.                 *to++ = c;
  65.                 w++;
  66.             }
  67.             bytes_written++;
  68.         }
  69.         if ((r = write(fd, buf, w)) != w)
  70.             return (r < 0) ? r : bytes_written - (w-r);
  71.     }
  72.     return bytes_written;
  73. }
  74.